﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zj.HttpCodeDemo.Domain.Interface;
using System.Data.SqlClient;
using System.ComponentModel;

namespace Zj.HttpCodeDemo.Repository
{
    public class BaseRepository<T>
        : IRepository<T>
        where T : class, new()
    {
        public void BulkInsert(IDbConnection myConn, IList<T> list)
        {
            if (myConn.State!= ConnectionState.Open)
            {
                myConn.Open();
            }

            using (var bulkCopy = new SqlBulkCopy((SqlConnection)myConn))
            {
                bulkCopy.DestinationTableName = $"[{typeof(T).Name}]";
                bulkCopy.BatchSize = list.Count;

               //var props_= TypeDescriptor.GetProperties(typeof(T))
               //     .Cast<PropertyDescriptor>()
               //     .Where(p => p.PropertyType.Namespace.Equals("System"))
               //     .ToArray();
               // var props__ = typeof(T).GetProperties()
               //     .Where(p => p.PropertyType.Namespace.StartsWith("System", StringComparison.OrdinalIgnoreCase))
               //     .ToArray();
                var props = typeof(T).GetProperties()
                    .Where(p => p.PropertyType.Namespace.Equals("System", StringComparison.OrdinalIgnoreCase))
                    .ToArray();

                var dt = new DataTable();
                foreach (var prop in props)
                {
                    bulkCopy.ColumnMappings.Add(prop.Name, prop.Name);
                    dt.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
                }

                var values = new object[props.Length];
                foreach (var item in list)
                {
                    for (int i = 0; i < props.Length; i++)
                    {
                        values[i] = props[i].GetValue(item);
                    }
                    dt.Rows.Add(values);
                }
                bulkCopy.WriteToServer(dt);
            }
        }
    }
}
